package com.train.base.service.impl;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserPost;
import com.ruoyi.common.enums.DictDataTypeEnums;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SnowflakeIdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import com.train.base.converter.AnswerConverter;
import com.train.base.domain.ExamGradingPaperRecord;
import com.train.base.domain.ExamPlan;
import com.train.base.domain.ExamQuestionBank;
import com.train.base.domain.ExamRecord;
import com.train.base.domain.ExamTestPaper;
import com.train.base.domain.ExamTestPaperModule;
import com.train.base.domain.PostImproveApplication;
import com.train.base.entity.bo.HistoryExam;
import com.train.base.entity.bo.PaperAnswer;
import com.train.base.entity.bo.PaperGradingRecord;
import com.train.base.entity.bo.PassRate;
import com.train.base.entity.bo.Question;
import com.train.base.enums.ExamTestPaperStateEnums;
import com.train.base.enums.PlanStatusEnums;
import com.train.base.enums.PostImproveApprovedStateEnums;
import com.train.base.enums.PostImproveTypeEnums;
import com.train.base.enums.QuestionTypeEnums;
import com.train.base.enums.ResultTypeEnums;
import com.train.base.mapper.ExamTestPaperMapper;
import com.train.base.service.IExamPlanService;
import com.train.base.service.IExamQuestionBankService;
import com.train.base.service.IExamTestPaperModuleService;
import com.train.base.service.IExamTestPaperService;
import com.train.base.service.IPostImproveApplicationService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 试卷管理Service业务层处理
 *
 * @author keke
 * @date 2024-04-01
 */
@Service
public class ExamTestPaperServiceImpl implements IExamTestPaperService {
    @Autowired
    private ExamTestPaperMapper examTestPaperMapper;
    @Autowired
    private IExamTestPaperModuleService examTestPaperModuleService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysPostService sysPostService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private IExamQuestionBankService iExamQuestionBankService;
    @Autowired
    private IExamPlanService iExamPlanService;
    @Autowired
    private AnswerConverter answerConverter;
    @Autowired
    private IPostImproveApplicationService iPostImproveApplicationService;
    @Autowired
    private ISysDictDataService iSysDictDataService;

    /**
     * 查询试卷管理
     *
     * @param id 试卷管理主键
     * @return 试卷管理
     */
    @Override
    public ExamTestPaper selectExamTestPaperById(Long id) {
        ExamTestPaper examTestPaper = examTestPaperMapper.selectExamTestPaperById(id);
        if (StringUtils.isNotNull(examTestPaper.getUserId())) {
            SysUser sysUser = iSysUserService.selectUserById(examTestPaper.getUserId());
            examTestPaper.setUserName(sysUser.getNickName());
        }
        return examTestPaper;
    }

    /**
     * 查询试卷管理列表
     *
     * @param examTestPaper 试卷管理
     * @return 试卷管理
     */
    @Override
    public List<ExamTestPaper> selectExamTestPaperList(ExamTestPaper examTestPaper) {
        List<ExamTestPaper> testPapers = examTestPaperMapper.selectExamTestPaperList(examTestPaper);
        if (testPapers.isEmpty()) {
            return Collections.emptyList();
        }
        List<Long> moduleIds = testPapers.stream().map(ExamTestPaper::getTestPaperModuleId).collect(Collectors.toSet()).stream().toList();
        List<ExamTestPaperModule> modules = examTestPaperModuleService.selectExamTestPaperModuleByIds(moduleIds);
        Map<Long, String> moduleMap = modules.stream().collect(Collectors.toMap(ExamTestPaperModule::getId, ExamTestPaperModule::getName));
        List<Long> userIds = testPapers.stream().map(ExamTestPaper::getUserId).collect(Collectors.toSet()).stream().toList();
        List<SysUser> sysUsers = iSysUserService.selectUserByIds(userIds);
        Map<Long, String> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        List<Long> planIds = testPapers.stream().map(ExamTestPaper::getExemPlanId).collect(Collectors.toSet()).stream().toList();
        List<ExamPlan> plans = iExamPlanService.selectExamPlanByIds(planIds);
        Map<Long, String> planMap = plans.stream().collect(Collectors.toMap(ExamPlan::getId, ExamPlan::getName));
        List<Long> deptIds = testPapers.stream().map(ExamTestPaper::getDeptId).collect(Collectors.toSet()).stream().toList();
        List<SysDept> depts = iSysDeptService.selectDeptByIds(deptIds);
        Map<Long, String> deptMap = depts.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName));
        List<Long> postIds = testPapers.stream().map(ExamTestPaper::getPostId).collect(Collectors.toSet()).stream().toList();
        List<SysPost> posts = sysPostService.selectPostListByIds(postIds);
        Map<Long, String> postMap = posts.stream().collect(Collectors.toMap(SysPost::getPostId, SysPost::getPostName));
        testPapers.forEach(e -> {
            e.setStateStr(ExamTestPaperStateEnums.getValueByCode(e.getState()));
            e.setTestPaperModuleName(moduleMap.get(e.getTestPaperModuleId()));
            e.setExamPlanName(planMap.get(e.getExemPlanId()));
            e.setUserName(userMap.get(e.getUserId()));
            e.setPostName(postMap.get(e.getPostId()));
            e.setDeptName(deptMap.get(e.getDeptId()));
        });
        return testPapers;
    }

    /**
     * 新增试卷管理
     *
     * @param examTestPaper 试卷管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertExamTestPaper(ExamTestPaper examTestPaper) {
        examTestPaper.setCreateTime(LocalDateTime.now());
        examTestPaper.setId(SnowflakeIdWorker.build().nextId());
        int rows = examTestPaperMapper.insertExamTestPaper(examTestPaper);
        insertExamRecord(examTestPaper);
        return rows;
    }

    /**
     * 修改试卷管理
     *
     * @param examTestPaper 试卷管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateExamTestPaper(ExamTestPaper examTestPaper) {
        examTestPaper.setUpdateTime(DateUtils.getNowDate());
        examTestPaperMapper.deleteExamRecordByTestPaperId(examTestPaper.getId());
        insertExamRecord(examTestPaper);
        return examTestPaperMapper.updateExamTestPaper(examTestPaper);
    }

    /**
     * 批量删除试卷管理
     *
     * @param ids 需要删除的试卷管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteExamTestPaperByIds(Long[] ids) {
        examTestPaperMapper.deleteExamRecordByTestPaperIds(ids);
        return examTestPaperMapper.deleteExamTestPaperByIds(ids);
    }

    /**
     * 删除试卷管理信息
     *
     * @param id 试卷管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteExamTestPaperById(Long id) {
        examTestPaperMapper.deleteExamRecordByTestPaperId(id);
        return examTestPaperMapper.deleteExamTestPaperById(id);
    }

    @Override
    @Transactional
    public List<Question> receive(Long id) {
        // 领取试卷的过程中同步生成数据
        ExamTestPaper examTestPaper = examTestPaperMapper.selectExamTestPaperById(id);
        if (!examTestPaper.getUserId().equals(SecurityUtils.getUserId())) {
            throw new BaseException("当前用户能领取该试卷");
        }
        if (examTestPaper.getState() != ExamTestPaperStateEnums.WAIT_RECEIVE.getCode()) {
            throw new BaseException("该试卷不允许进行领取");
        }
        ExamTestPaperModule examTestPaperModule = examTestPaperModuleService.selectExamTestPaperModuleById(examTestPaper.getTestPaperModuleId());
        // 根据规则生成试题
        List<Question> questions = examTestPaperModuleService.createPaper(examTestPaperModule);
        QuestionToRecord(questions, id);
        examTestPaperMapper.updateState(id, ExamTestPaperStateEnums.WAIT_SUBMIT.getCode());
        return questions;
    }

    @Override
    public void batchInsertExamTestPaper(List<ExamTestPaper> testPapers) {
        examTestPaperMapper.batchInsertExamTestPaper(testPapers);
    }

    @Override
    public List<Question> getDetail(Long id) {
        ExamTestPaper examTestPaper = examTestPaperMapper.selectExamTestPaperById(id);
        List<ExamRecord> examRecordList = examTestPaper.getExamRecordList();
        List<Long> recordIds = examRecordList.stream().map(ExamRecord::getId).toList();
        List<ExamQuestionBank> banks = iExamQuestionBankService.selectExamQuestionBankByIds(examTestPaper.getExamRecordList().stream().map(ExamRecord::getQuestionId).toList());
        Map<Long, ExamQuestionBank> bankMap = banks.stream().collect(Collectors.toMap(ExamQuestionBank::getId, Function.identity()));
        List<Question> questions = new ArrayList<>();
        for (ExamRecord e : examTestPaper.getExamRecordList()) {
            ExamQuestionBank b = bankMap.get(e.getQuestionId());
            Question question = getQuestion(e, b);
            questions.add(question);
        }
        return questions.stream().sorted(Comparator.comparing(Question::getType)).toList();
    }

    @Override
    @Transactional
    public int submitPaper(PaperAnswer answer) {
        long rightAnswerNum = 0, notDoneNum = 0, vagueNum = 0;
        List<ExamQuestionBank> banks = iExamQuestionBankService.selectExamQuestionBankByIds(answer.getAnswers().stream().map(PaperAnswer.Answer::getQuestionId).toList());
        Map<Long, ExamQuestionBank> bankMap = banks.stream().collect(Collectors.toMap(ExamQuestionBank::getId, Function.identity()));
        Double gainGrade = 0d;
        for (PaperAnswer.Answer answerAnswer : answer.getAnswers()) {
            if (Objects.nonNull(answerAnswer.getGainGrade())) {
                gainGrade += answerAnswer.getGainGrade();
            }
            if (answerAnswer.getResult().equals(2L)) {
                rightAnswerNum++;
            } else if (StringUtils.isEmpty(answerAnswer.getContent())) {
                notDoneNum++;
            }
            ExamQuestionBank bank = bankMap.get(answerAnswer.getQuestionId());
            if (bank.getQuestionType().equals(QuestionTypeEnums.EssayQuestion.getCode())) {
                vagueNum++;
                answerAnswer.setResult(null);
                answerAnswer.setGainGrade(null);
            }
            ExamRecord record = answerConverter.answerToExamRecord(answerAnswer);
            examTestPaperMapper.updateExamRecord(record);
        }
        ExamTestPaper examTestPaper = new ExamTestPaper();
        examTestPaper.setId(answer.getPaperId());
        examTestPaper.setRightAnswerNum(rightAnswerNum);
        examTestPaper.setNotDoneNum(notDoneNum);
        examTestPaper.setVagueNum(vagueNum);
        examTestPaper.setSubmitTime(new Date());
        examTestPaper.setGainGrade(gainGrade);
        if (vagueNum > 0) {
            examTestPaper.setState(ExamTestPaperStateEnums.WAIT_GRADE.getCode());
        } else {
            examTestPaper.setState(ExamTestPaperStateEnums.FINISH.getCode());
            finishExamTestPaper(examTestPaper);
        }
        return examTestPaperMapper.updateExamTestPaper(examTestPaper);
    }

    @Override
    @Transactional
    public int gradingPaper(PaperGradingRecord paperGradingRecord) {
        // 将批阅记录记录到本地
        List<ExamGradingPaperRecord> records = new ArrayList<>();
        paperGradingRecord.getGradingPapers().forEach(r -> {
            ExamGradingPaperRecord record = new ExamGradingPaperRecord();
            record.setId(SnowflakeIdWorker.build().nextId());
            record.setRecordId(r.getRecordId());
            record.setResult(r.getResult());
            record.setGainGrade(r.getGainGrade());
            record.setRemark(r.getRemark());
            record.setCreateBy(SecurityUtils.getUsername());
            record.setIsDel(0L);
            records.add(record);
        });
        examTestPaperMapper.batchInsertGradingRecord(records);
        // 更新试卷回填记录
        Map<Long, PaperGradingRecord.GradingPaper> gradingPaperMap = paperGradingRecord.getGradingPapers().stream().collect(Collectors.toMap(PaperGradingRecord.GradingPaper::getRecordId, Function.identity()));
        ExamTestPaper examTestPaper = examTestPaperMapper.selectExamTestPaperById(paperGradingRecord.getPaperId());
        Double allGrade = 0D, allGainGrade = 0D;
        for (ExamRecord r : examTestPaper.getExamRecordList()) {
            if (gradingPaperMap.keySet().contains(r.getId())) {
                PaperGradingRecord.GradingPaper gradingPaper = gradingPaperMap.get(r.getId());
                r.setGainGrade(gradingPaper.getGainGrade());
                r.setResult(gradingPaper.getResult());
                examTestPaperMapper.updateExamRecord(r);
            }
            allGrade += r.getGrade();
            if (Objects.nonNull(r.getGainGrade())) {
                allGainGrade += r.getGainGrade();
            }
        }
        // 更新试卷信息
        examTestPaper.setGainGrade(allGainGrade);
        examTestPaper.setState(ExamTestPaperStateEnums.FINISH.getCode());
        // 更新试卷的状态
        int result = examTestPaperMapper.updateExamTestPaper(examTestPaper);
        // 完成后的处理逻辑
        finishExamTestPaper(examTestPaper);
        return result;
    }

    @Override
    public List<ExamTestPaper> listByDate(LocalDate month) {
        return examTestPaperMapper.listByDate(SecurityUtils.getUserId(), month);
    }

    @Override
    public List<ExamTestPaper> selectExamTestPaperByPlanIds(List<Long> planIds) {
        return examTestPaperMapper.selectExamTestPaperByPlanIds(planIds);
    }

    @Override
    public Map<Integer, List<ExamTestPaper>> examRanking() {
        Map<Integer, List<ExamTestPaper>> examTestPaperMap = new HashMap<>();
        // 查询考试数据
        List<Long> planIds = iExamPlanService.selectExamPlanOrderByCreateTime(3);
        planIds.forEach(planId -> {
            List<ExamTestPaper> testPapers = examTestPaperMapper.selectExamTestForRank(planId);
            List<Long> userIds = testPapers.stream().map(ExamTestPaper::getUserId).collect(Collectors.toSet()).stream().toList();
            if (!ObjectUtils.isEmpty(userIds)) {
                List<SysUser> sysUsers = iSysUserService.selectUserByIds(userIds);
                Map<Long, String> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
                testPapers.forEach(e -> e.setUserName(userMap.get(e.getUserId())));
            }
            for (int i = 0; i < planIds.size(); i++) {
                examTestPaperMap.put(i, testPapers);
            }
        });
        return examTestPaperMap;
    }

    @Override
    public List<PassRate> passRate() {
        List<PassRate> passRates = new ArrayList<>();
        // 查询考试计划信息
        List<Long> planIds = iExamPlanService.selectExamPlanOrderByCreateTime(10);
        if(planIds.isEmpty()){
            return Collections.emptyList();
        }
        List<ExamTestPaper> testPapers = examTestPaperMapper.selectExamTestPaperByPlanIds(planIds);
        Map<Long, List<ExamTestPaper>> paperMap = testPapers.stream().collect(Collectors.groupingBy(ExamTestPaper::getExemPlanId));
        // 查询模板信息
        List<ExamPlan> examPlans = iExamPlanService.selectExamPlanByIds(planIds);
        List<Long> moduleIds = examPlans.stream().map(ExamPlan::getExamTestPaperModuleId).toList();
        Map<Long, ExamTestPaperModule> moduleMap = examTestPaperModuleService.selectExamTestPaperModuleByIds(moduleIds).stream().collect(Collectors.toMap(ExamTestPaperModule::getId, Function.identity()));
        paperMap.forEach((k, v) -> {
            int passNum = 0;
            Long passGrade = moduleMap.get(v.get(0).getTestPaperModuleId()).getPassGrade();
            PassRate rate = new PassRate();
            rate.setPaperId(v.get(0).getId());
            rate.setPaperName(v.get(0).getName());
            for (ExamTestPaper r : v) {
                if (r.getGainGrade() >= passGrade) {
                    passNum++;
                }
            }
            rate.setPassRate((double) passNum / v.size());
            passRates.add(rate);
        });
        return passRates;
    }

    @Override
    public List<HistoryExam> historyExamFirst() {
        List<HistoryExam> historyExams = new ArrayList<>();
        // 查询考试计划
        ExamPlan examPlan = new ExamPlan();
        examPlan.setStatu(PlanStatusEnums.FINISH.getCode());
        List<ExamPlan> examPlans = iExamPlanService.selectExamPlanList(examPlan);
        if (ObjectUtils.isEmpty(examPlans)) {
            return historyExams;
        }
        List<Long> planIds = examPlans.stream().map(ExamPlan::getId).toList();
        planIds.forEach(planId -> {
            ExamTestPaper paper = examTestPaperMapper.selectExamPaperByPlanId(planId);
            if (!ObjectUtils.isEmpty(paper)) {
                HistoryExam history = new HistoryExam();
                history.setPaperId(paper.getId());
                history.setPaperName(paper.getName());
                history.setUserId(paper.getUserId());
                history.setGrade(paper.getGrade());
                history.setGainGrade(paper.getGainGrade());
                historyExams.add(history);
            }
        });
        // 添加用户名
        if (!ObjectUtils.isEmpty(historyExams)) {
            List<Long> userIds = historyExams.stream().map(HistoryExam::getUserId).toList();
            Map<Long, String> userMap = iSysUserService.selectUserByIds(userIds).stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
            historyExams.forEach(h -> h.setUserName(userMap.get(h.getUserId())));
        }
        return historyExams;
    }

    @Override
    public Map<String, Integer> errorProportion() {
        Map<String, Integer> map = new HashMap<>();
        // 查询题的总数量
        Integer count = examTestPaperMapper.count(new ExamRecord());
        // 查询错误题的数量
        ExamRecord record = new ExamRecord();
        record.setResult(ResultTypeEnums.ERROR.getCode());
        Integer errorCount = examTestPaperMapper.count(record);
        map.put("all", count);
        map.put("error", errorCount);
        return map;
    }

    @Override
    public ExamTestPaper selectExamTestPaperByUserId(Long userId, Long postId) {
        return examTestPaperMapper.selectExamTestPaperByUserId(userId, postId);
    }

    /**
     * 完成后的处理逻辑
     *
     * @param examTestPaper
     */
    private void finishExamTestPaper(ExamTestPaper examTestPaper) {
        ExamTestPaper testPaper = examTestPaperMapper.selectExamTestPaperById(examTestPaper.getId());
        testPaper.setGainGrade(examTestPaper.getGainGrade());
        ExamTestPaper paper = new ExamTestPaper();
        paper.setExemPlanId(testPaper.getExemPlanId());
        List<ExamTestPaper> papers = examTestPaperMapper.selectExamTestPaperList(paper);
        List<ExamTestPaper> list = papers.stream().filter(e -> !e.getState().equals(ExamTestPaperStateEnums.FINISH.getCode())).toList();
        if (list.size() == 1) {
            Long id = list.get(0).getId();
            if (id.equals(testPaper.getId())) {
                // 将计划结束
                iExamPlanService.finish(testPaper.getExemPlanId());
            }
        }
        ExamPlan examPlan = iExamPlanService.selectExamPlanById(testPaper.getExemPlanId());
        ExamTestPaperModule examTestPaperModule = examTestPaperModuleService.selectExamTestPaperModuleById(examPlan.getExamTestPaperModuleId());
        // 如果及格的操作
        if (examTestPaperModule.getPassGrade() <= testPaper.getGainGrade()) {
//            improvePostLevelAndAbility(testPaper, examTestPaperModule);
        } else {
            // 不及格
            // todo 补考逻辑取消
//            if (examPlan.getWhetherCanResit().equals(WhetherCanResitEnums.CAN.getCode())) {
//                // 如果可以补考，则重新生成一个试卷进行补考
//                ExamTestPaper paper = new ExamTestPaper();
//                paper.setId(SnowflakeIdWorker.build().nextId());
//                paper.setName("补考" + examTestPaper.getName());
//                paper.setQuestionNum(examTestPaper.getQuestionNum());
//                paper.setExemPlanId(examTestPaper.getExemPlanId());
//                paper.setState(ExamTestPaperStateEnums.WAIT_RECEIVE.getCode());
//                paper.setTestPaperModuleId(examTestPaper.getTestPaperModuleId());
//                paper.setUserId(examTestPaper.getUserId());
//                paper.setGrade(examTestPaper.getGrade());
//                paper.setDeptId(examTestPaper.getDeptId());
//                paper.setPostId(examTestPaper.getPostId());
//                paper.setPostLevelCode(examTestPaper.getPostLevelCode());
//                examTestPaperMapper.insertExamTestPaper(paper);
//            }
        }
    }

    /**
     * 提升岗位级别和岗位能力
     *
     * @param examTestPaper
     * @param examTestPaperModule
     */
    private void improvePostLevelAndAbility(ExamTestPaper examTestPaper, ExamTestPaperModule examTestPaperModule) {
        if (examTestPaperModule.getPostLevelCode().equals(examTestPaper.getPostLevelCode())) {
            // 发起提升岗位级别申请
            {
                PostImproveApplication application = new PostImproveApplication();
                application.setId(SnowflakeIdWorker.build().nextId());
                application.setPostId(examTestPaper.getPostId());
                application.setReviewer(SecurityUtils.getUserId());
                application.setOldCode(examTestPaper.getPostLevelCode());
                application.setState(PostImproveApprovedStateEnums.WAIT.getCode());
                Integer newLevel = Integer.valueOf(examTestPaper.getPostLevelCode()) + 1;
                if (iSysDictDataService.selectDictLabel(DictDataTypeEnums.POST_LEVEL.getCode(), String.valueOf(newLevel)) != null) {
                    application.setToCode(String.valueOf(newLevel));
                    application.setType(PostImproveTypeEnums.LEVEL.getCode());
                    iPostImproveApplicationService.insertPostImproveApplication(application);
                }
            }
            // 发起提升岗位能力申请

            {
                String oldAbility = null;
                Long postId = null;
                SysUser sysUser = iSysUserService.selectUserById(examTestPaper.getUserId());
                List<SysUserPost> sysUserPosts = iSysUserService.selectPostWithLevel(examTestPaper.getUserId());
                for (SysUserPost sysUserPost : sysUserPosts) {
                    if (sysUserPost.getPostId().equals(examTestPaper.getPostId())) {
                        oldAbility = sysUserPost.getPostAbility();
                        postId = sysUserPost.getPostId();
                    }
                }
                if (Objects.nonNull(oldAbility)) {
                    PostImproveApplication application = new PostImproveApplication();
                    application.setPostId(postId);
                    application.setId(SnowflakeIdWorker.build().nextId());
                    application.setReviewer(SecurityUtils.getUserId());
                    application.setOldCode(oldAbility);
                    application.setState(PostImproveApprovedStateEnums.WAIT.getCode());
                    Integer newAbility = Integer.valueOf(oldAbility) + 1;
                    if (iSysDictDataService.selectDictLabel(DictDataTypeEnums.POST_ABILITY.getCode(), String.valueOf(newAbility)) != null) {
                        application.setToCode(String.valueOf(newAbility));
                        application.setType(PostImproveTypeEnums.ABILITY.getCode());
                        iPostImproveApplicationService.insertPostImproveApplication(application);
                    }
                }
            }
        }
    }

    @NotNull
    private static Question getQuestion(ExamRecord e, ExamQuestionBank b) {
        Question question = new Question();
        question.setRecordId(e.getId());
        question.setQuestionId(b.getId());
        question.setGrade(e.getGrade());
        question.setResult(e.getResult());
        question.setGainGrade(e.getGainGrade());
        question.setResultContent(e.getContent());
        question.setType(b.getQuestionType());
        question.setAnalysis(b.getAnalysis());
        question.setContent(b.getContent());
        question.setRightKey(b.getRightKey());
        question.setExamQuestionBankOptionList(b.getExamQuestionBankOptionList());
        return question;
    }

    /**
     * 新增考试记录信息
     *
     * @param examTestPaper 试卷管理对象
     */
    public void insertExamRecord(ExamTestPaper examTestPaper) {
        List<ExamRecord> examRecordList = examTestPaper.getExamRecordList();
        Long id = examTestPaper.getId();
        if (StringUtils.isNotNull(examRecordList)) {
            List<ExamRecord> list = new ArrayList<ExamRecord>();
            for (ExamRecord examRecord : examRecordList) {
                examRecord.setTestPaperId(id);
                list.add(examRecord);
            }
            if (!list.isEmpty()) {
                examTestPaperMapper.batchExamRecord(list);
            }
        }
    }

    private void QuestionToRecord(List<Question> questions, Long testPaperId) {
        List<ExamRecord> records = new ArrayList<>();
        for (Question e : questions) {
            ExamRecord record = new ExamRecord();
            record.setId(SnowflakeIdWorker.build().nextId());
            record.setGrade(e.getGrade());
            record.setTestPaperId(testPaperId);
            record.setQuestionId(e.getQuestionId());
            record.setUserId(SecurityUtils.getUserId());
            record.setIsDel(0L);
            records.add(record);
            e.setRecordId(record.getId());
        }
        examTestPaperMapper.batchExamRecord(records);
    }
}
